package cn.sytton.taffecloud.common.api.decoder;

import cn.sytton.taffecloud.common.base.exception.ApiException;
import cn.sytton.taffecloud.common.base.response.R;
import cn.sytton.taffecloud.common.base.util.JsonUtil;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * 封装返回结果
 *
 * @author skyrock
 */
@Configuration
public class FeignResultDecoder implements Decoder {

    @Value("${feign.global-exception:true}")
    private boolean enabledGlobalException;

    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
        //手动重新转换ResponseResult类型，解决返回的String处理错误
        R<?> r = JsonUtil.getEntity(bodyStr, R.class);
        assert r != null;
        if (!r.isSuccess() && enabledGlobalException) {
            //不启用全局异常，并且返回错误的情况下，抛出异常，对于seata的分布事物有效
            throw new ApiException(r.getMessage());
        } else {
            return r;
        }
    }
}
